const pool = require('../models/db');

const commentController = {
    // 获取文章的所有评论
    getArticleComments: async (req, res) => {
        try {
            // 获取所有评论
            const [comments] = await pool.query(`
                SELECT 
                    c.id,
                    c.content,
                    c.created_at,
                    c.parent_id,
                    c.user_id,
                    c.nickname,
                    c.email,
                    u.username,
                    u.avatar_url
                FROM comments c
                LEFT JOIN users u ON c.user_id = u.id
                WHERE c.article_id = ?
                ORDER BY c.created_at DESC
            `, [req.params.articleId]);

            // 构建评论树结构
            const commentTree = [];
            const commentMap = {};

            // 首先将所有评论放入 map 中
            comments.forEach(comment => {
                commentMap[comment.id] = {
                    ...comment,
                    replies: []
                };
            });

            // 构建树结构
            comments.forEach(comment => {
                if (comment.parent_id) {
                    // 如果有父评论，将其添加到父评论的 replies 中
                    if (commentMap[comment.parent_id]) {
                        commentMap[comment.parent_id].replies.push(commentMap[comment.id]);
                    }
                } else {
                    // 如果是顶级评论，直接添加到结果数组
                    commentTree.push(commentMap[comment.id]);
                }
            });

            res.json(commentTree);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 获取单个评论
    getCommentById: async (req, res) => {
        try {
            const commentId = parseInt(req.params.id);
            
            // 验证ID是否为有效数字
            if (isNaN(commentId)) {
                return res.status(400).json({ message: '无效的评论ID' });
            }
    
            // 获取评论详情，包括用户信息和文章信息
            const [comments] = await pool.query(`
                SELECT 
                    c.*,
                    COALESCE(c.nickname, u.username) as author_name,
                    COALESCE(c.email, u.email) as author_email,
                    u.avatar_url as author_avatar,
                    a.title as article_title,
                    a.id as article_id
                FROM comments c
                LEFT JOIN users u ON c.user_id = u.id
                LEFT JOIN articles a ON c.article_id = a.id
                WHERE c.id = ?
            `, [commentId]);
    
            if (comments.length === 0) {
                return res.status(404).json({ message: '评论不存在' });
            }
    
            const comment = comments[0];
    
            // 如果是回复评论，获取父评论信息
            if (comment.parent_id) {
                const [parentComments] = await pool.query(`
                    SELECT 
                        c.*,
                        COALESCE(c.nickname, u.username) as author_name,
                        COALESCE(c.email, u.email) as author_email
                    FROM comments c
                    LEFT JOIN users u ON c.user_id = u.id
                    WHERE c.id = ?
                `, [comment.parent_id]);
    
                if (parentComments.length > 0) {
                    comment.parent_comment = parentComments[0];
                }
            }
    
            // 获取该评论的回复
            const [replies] = await pool.query(`
                SELECT 
                    c.*,
                    COALESCE(c.nickname, u.username) as author_name,
                    COALESCE(c.email, u.email) as author_email,
                    u.avatar_url as author_avatar
                FROM comments c
                LEFT JOIN users u ON c.user_id = u.id
                WHERE c.parent_id = ?
                ORDER BY c.created_at ASC
            `, [commentId]);
    
            // 添加回复到评论对象
            comment.replies = replies;
    
            res.json(comment);
        } catch (error) {
            console.error('获取评论失败:', error);
            res.status(500).json({ error: error.message });
        }
    },

    // 创建评论
    createComment: async (req, res) => {
        try {
            const { article_id, content, parent_id, nickname, email } = req.body;
            
            // 检查必要字段
            if (!article_id || !content) {
                return res.status(400).json({ error: '缺少必要字段' });
            }
    
            // 构建评论数据
            const commentData = {
                content,
                article_id,
                parent_id: parent_id || null,
                nickname: nickname || '匿名用户',
                email: email || null,
                user_id: req.user?.id || null  // 如果用户已登录，使用用户ID
            };
    
            // 插入评论
            const [result] = await pool.query(
                `INSERT INTO comments SET ?`,
                commentData
            );
    
            // 更新文章评论数
            await pool.query(
                `UPDATE articles SET comment_count = comment_count + 1 WHERE id = ?`,
                [article_id]
            );
    
            // 获取新插入的评论详情
            const [comment] = await pool.query(
                `SELECT * FROM comments WHERE id = ?`,
                [result.insertId]
            );
    
            res.status(201).json(comment[0]);
        } catch (error) {
            console.error('添加评论失败:', error);
            res.status(500).json({ error: error.message });
        }
    },

    // 更新评论
    updateComment: async (req, res) => {
        try {
            const { content } = req.body;
            const [result] = await pool.query(
                `UPDATE comments 
                SET content = ?
                WHERE id = ?`,
                [content, req.params.id]
            );

            if (result.affectedRows === 0) {
                return res.status(404).json({ message: '评论不存在' });
            }

            // 获取更新后的评论
            const [updatedComment] = await pool.query(`
                SELECT 
                    c.*,
                    u.username,
                    u.avatar_url
                FROM comments c
                LEFT JOIN users u ON c.user_id = u.id
                WHERE c.id = ?
            `, [req.params.id]);

            res.json({
                message: '评论更新成功',
                comment: updatedComment[0]
            });
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 删除评论
    deleteComment: async (req, res) => {
        try {
            const connection = await pool.getConnection();
            try {
                await connection.beginTransaction();

                // 获取评论信息
                const [comment] = await connection.query(
                    'SELECT article_id FROM comments WHERE id = ?',
                    [req.params.id]
                );

                if (comment.length === 0) {
                    await connection.rollback();
                    return res.status(404).json({ message: '评论不存在' });
                }

                // 删除评论及其所有子评论
                const [result] = await connection.query(
                    `WITH RECURSIVE CommentTree AS (
                        SELECT id, article_id FROM comments WHERE id = ?
                        UNION ALL
                        SELECT c.id, c.article_id
                        FROM comments c
                        JOIN CommentTree ct ON c.parent_id = ct.id
                    )
                    DELETE c FROM comments c
                    JOIN CommentTree ct ON c.id = ct.id`,
                    [req.params.id]
                );

                // 更新文章的评论计数
                await connection.query(
                    `UPDATE articles 
                    SET comment_count = comment_count - ?
                    WHERE id = ?`,
                    [result.affectedRows, comment[0].article_id]
                );

                await connection.commit();
                res.json({ 
                    message: '评论删除成功',
                    deletedCount: result.affectedRows
                });
            } catch (error) {
                await connection.rollback();
                throw error;
            } finally {
                connection.release();
            }
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 获取用户的所有评论
    getUserComments: async (req, res) => {
        try {
            const [comments] = await pool.query(`
                SELECT 
                    c.*,
                    a.title as article_title,
                    u.username,
                    u.avatar_url
                FROM comments c
                LEFT JOIN articles a ON c.article_id = a.id
                LEFT JOIN users u ON c.user_id = u.id
                WHERE c.user_id = ?
                ORDER BY c.created_at DESC
            `, [req.params.userId]);

            res.json(comments);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 获取文章的顶级评论
    getComments : async (req, res) => {
        try {
            const { articleId } = req.params;
            
            // 获取所有顶级评论
            const [comments] = await pool.query(
                `SELECT 
                    c.*,
                    COALESCE(c.nickname, u.username) as author_name,
                    COALESCE(c.email, u.email) as author_email
                FROM comments c
                LEFT JOIN users u ON c.user_id = u.id
                WHERE c.article_id = ? AND c.parent_id IS NULL
                ORDER BY c.created_at DESC`,
                [articleId]
            );
    
            // 获取每个顶级评论的回复
            for (let comment of comments) {
                const [replies] = await pool.query(
                    `SELECT 
                        c.*,
                        COALESCE(c.nickname, u.username) as author_name,
                        COALESCE(c.email, u.email) as author_email
                    FROM comments c
                    LEFT JOIN users u ON c.user_id = u.id
                    WHERE c.parent_id = ?
                    ORDER BY c.created_at ASC`,
                    [comment.id]
                );
                comment.replies = replies;
            }
    
            res.json(comments);
        } catch (error) {
            console.error('获取评论失败:', error);
            res.status(500).json({ error: error.message });
        }
    }
};

module.exports = commentController;